from collections import OrderedDict
from django.conf import settings
from django.template import loader
from goods.models import GoodsChannel
from .models import ContentCategory
import time
import os

if not os.getenv('DJANGO_SETTINGS_MODULE'):
    os.environ['DJANGO_SETTINGS_MODULE'] = 'meiduo_mall.settings.dev'


# 处理页面静态化的逻辑

"""
1.交互式命令行生成静态文件：
(django_py3) python@ubuntu:~/PycharmProjects/meiduo_mall_Django/meiduo_mall$ python manage.py shell
Python 3.5.2 (default, Nov 17 2016, 17:05:23) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from ads.crons import generate_static_index_html
>>> generate_static_index_html()
Sun Jul 15 11:44:08 2018: generate_static_index_html

"""

#  页面静态化需要先启动容器
# http://127.0.0.1:8080/
# http://127.0.0.1:8080/index.html

"""
2.可以通过定时任务生成静态文件

添加定时任务到系统中
python manage.py crontab add

显示已经激活的定时任务
python manage.py crontab show

移除定时任务
python manage.py crontab remove
"""

"""
3.通过脚本手动生成静态文件
scripts/regenerate_index_html.py
"""


def generate_static_index_html():
    """
    生成静态的主页html文件,出现的目录在配置文件中配置
    """
    print('%s: generate_static_index_html' % time.ctime())
    # 商品频道及分类菜单
    # 使用有序字典保存类别的顺序
    # categories = {
    #     1: { # 组1
    #         'channels': [{'id':, 'name':, 'url':},{}, {}...],
    #         'sub_cats': [{'id':, 'name':, 'sub_cats':[{},{}]}, {}, {}, ..]
    #     },
    #     2: { # 组2
    #
    #     }
    # }

    # OrderedDict  python自带的序列化器
    categories = OrderedDict()
    channels = GoodsChannel.objects.order_by('group_id', 'sequence')
    for channel in channels:
        group_id = channel.group_id  # 当前组

        if group_id not in categories:
            categories[group_id] = {'channels': [], 'sub_cats': []}

        cat1 = channel.category  # 当前频道的类别

        # 追加当前频道
        categories[group_id]['channels'].append({
            'id': cat1.id,
            'name': cat1.name,
            'url': channel.url
        })
        # 构建当前类别的子类别
        for cat2 in cat1.goodscategory_set.all():
            cat2.sub_cats = []
            for cat3 in cat2.goodscategory_set.all():
                cat2.sub_cats.append(cat3)
            categories[group_id]['sub_cats'].append(cat2)

    # 广告内容
    contents = {}
    content_categories = ContentCategory.objects.all()
    for cat in content_categories:
        contents[cat.key] = cat.content_set.filter(status=True).order_by('sequence')

    # 渲染模板
    context = {
        'categories': categories,
        'contents': contents
    }
    template = loader.get_template('index.html')
    html_text = template.render(context)
    file_path = os.path.join(settings.GENERATED_STATIC_HTML_FILES_DIR, 'index.html')
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(html_text)




